package com.smart.community.commons.monitor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.concurrent.atomic.AtomicLong;

/**
 * SQL执行时间监控器
 * 
 * @author Wu.Liang
 */
@Slf4j
@Component
public class SqlExecutionTimeMonitor {
    
    private final AtomicLong totalExecutions = new AtomicLong(0);
    private final AtomicLong totalExecutionTime = new AtomicLong(0);
    private final AtomicLong slowQueryCount = new AtomicLong(0);
    
    private static final long SLOW_QUERY_THRESHOLD = 1000; // 1秒
    
    /**
     * 记录SQL执行
     */
    public void recordExecution(String sql, long executionTime) {
        totalExecutions.incrementAndGet();
        totalExecutionTime.addAndGet(executionTime);
        
        if (executionTime > SLOW_QUERY_THRESHOLD) {
            slowQueryCount.incrementAndGet();
            log.warn("慢查询检测: SQL={}, 执行时间={}ms", sql, executionTime);
        }
    }
    
    /**
     * 获取执行报告
     */
    public SqlExecutionReport getExecutionReport() {
        long total = totalExecutions.get();
        long totalTime = totalExecutionTime.get();
        long slowCount = slowQueryCount.get();
        
        double averageTime = total > 0 ? (double) totalTime / total : 0;
        double slowRate = total > 0 ? (double) slowCount / total * 100 : 0;
        
        return new SqlExecutionReport(total, averageTime, slowCount, slowRate);
    }
    
    /**
     * 重置统计
     */
    public void reset() {
        totalExecutions.set(0);
        totalExecutionTime.set(0);
        slowQueryCount.set(0);
    }
    
    /**
     * SQL执行报告
     */
    public static class SqlExecutionReport {
        private final long totalExecutions;
        private final double averageExecutionTime;
        private final long slowQueryCount;
        private final double slowQueryRate;
        
        public SqlExecutionReport(long totalExecutions, double averageExecutionTime, 
                                long slowQueryCount, double slowQueryRate) {
            this.totalExecutions = totalExecutions;
            this.averageExecutionTime = averageExecutionTime;
            this.slowQueryCount = slowQueryCount;
            this.slowQueryRate = slowQueryRate;
        }
        
        public long getTotalExecutions() { return totalExecutions; }
        public double getAverageExecutionTime() { return averageExecutionTime; }
        public long getSlowQueryCount() { return slowQueryCount; }
        public double getSlowQueryRate() { return slowQueryRate; }
    }
}
